package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * @author 21829
 */
@Component
public class RedisIdWorker {

    private static final Long BEGIN_TIMESTAMP = 1727740800L;

    private static final int COUNT_BITS = 32;

    private StringRedisTemplate stringRedisTemplate;

    public RedisIdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public Long nextId(String keyPrefix){
        LocalDateTime now = LocalDateTime.now();
        long nowEpochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long epochSecond = nowEpochSecond - BEGIN_TIMESTAMP;

        String data = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));

        Long increment = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + data);

        return increment << COUNT_BITS | epochSecond;

    }
}
